<?php
 $wojewodztwa = Array("dolnośląskie",
                        "kujawsko-pomorskie",
                        "lubelskie",
                        "lubuskie",
                        "Łódzkie",
                        "małopolskie",
                        "mazowieckie",
                        "opolskie",
                        "podkarpackie",
                        "podlaskie",
                        "pomorskie",
                        "Śląskie",
                        "Świętokrzyskie",
                        "warmińsko-mazurskie",
                        "wielkopolskie",
                        "zachodniopomorskie",
                        "za granicą");

   function WojewodztwaComboBox($name, $select="")
   {
      $wojewodztwa = Array("dolnośląskie",
                        "kujawsko-pomorskie",
                        "lubelskie",
                        "lubuskie",
                        "Łódzkie",
                        "małopolskie",
                        "mazowieckie",
                        "opolskie",
                        "podkarpackie",
                        "podlaskie",
                        "pomorskie",
                        "Śląskie",
                        "Świętokrzyskie",
                        "warmińsko-mazurskie",
                        "wielkopolskie",
                        "zachodniopomorskie",
                        "za granicą");
     $wojewodztwa_r.= "<script>
                        function PokUkKraj()
                        {
                          var row = document.getElementById('kraj_row');
                          if (document.forms[0].state.value == '17')
                           row.style.display = '';
                          else
                           row.style.display ='none';

                        }
                        </script>

     <select onchange='PokUkKraj();' name='".$name."'>
               <option value='0'>".__('-- wybierz --')."</option>";
     foreach ($wojewodztwa as $key => $woj)
     {
        $key+1 == $select ? $selected="SELECTED" : $selected ="";
        $wojewodztwa_r.="<option value='".($key+1)."' ".$selected.">".$woj."</option>";
     }
     $wojewodztwa_r.= "</select>";
     return $wojewodztwa_r;
   }

      function CutString($str)
         {
           $str = trim($str);
           $cut = array(" sp ", " sp.", " spółka ", "s.a.");
           $cut2 = array(" sc", "sa");
           foreach ($cut as $c)
           {
            $pos = stripos($str, $c);
            if ($pos)
               $str = substr($str, 0, $pos);
           }
           foreach ($cut2 as $c)
           {
             $pos = strripos($str, $c);
             if ($pos + 2 == strlen($str))
                $str = substr($str, 0, $pos);
           }

           return trim($str);

         }


   function CheckClient()
   {
     $str = CutString($_GET['name']);
        $words = explode(" ",$str);
     $query = "SELECT id, name FROM bazkl_clients WHERE upper(name) LIKE upper('%".implode("%') OR upper(name) LIKE upper('%",$words)."%')";
     $result = DBManager::getArrayData($query);
     echo mysql_error();

     if (count($result) == 0)
     {
       $clients = __("Nie ma takiego klienta w bazie");
     }
     else
     {
       $clients.=__("Znaleziono ").count($result).__(" klientów spełniających warunki:")."<br><br>";
       foreach($result as $data)
       {
         $clients.="<a href='index.php?action=clients&site=show&id=".$data['id']."'>".$data['name']."</a><br>";
       }
     }

     return $clients;
   }

   function PrintSimilarClientJNames( $name , $client_id){
     $name = str_replace("'","\'",$name);
//     $znakiDoWyciecia = array("\"","?","<",">","[","]",","," . "," .",". ",".","&");
//     $slowaDoWyciecia = array(" sp "," system "," systemy ","system ","systemy "," z "," o "," i "," oo ",
//			      " zoo "," spzoo "," spz "," u ","firma","polska","poland","international","group","services",
//                              "biuro","biura","spółka","spolka","grupa"," sa "," sp z o o"," - "," -","- ",
//                              "finansowe","rachunkowe","audytorskie","hotel","restauracja","zakład","centrum","architektoniczne",
//                              "architektoniczna","architektoniczny","architektoniczno"," sc "," sj "," sk ","pphu","phu","service",
//                              "agencja","polska","poland","przedsiębiorstwo","komandytowa");
//     $name = strtolower( $name );
//     $name = str_replace($znakiDoWyciecia,'',$name);
//     $name = str_replace($slowaDoWyciecia,' ',$name);
          $slowaDoWyciecia = array("SP","SYSTEM","SYSTEMY","Z","O","I","OO","O.","O.O.","SP.","O.O",
			      "ZOO","SPZOO","SPZ","U","FIRMA","POLSKA","INTERNATIONAL","GROUP","SERVICES",
                              "BIURO","BIURA","SPOLKA","GRUPA","SA","-","FINANSOWE","RACHUNKOWE","AUDYTORSKIE",
                              "HOTEL","RESTAURACJA","ZAKŁAD","CENTRUM","ARCHITEKTONICZNE",
                              "ARCHITEKTONICZNA","ARCHITEKTONICZNY","ARCHITEKTONICZNO","SC","SJ","SK","PPHU","PHU","SERVICE",
                              "AGENCJA","POLAND","PRZEDSIĘBIORSTWO","KOMANDYTOWA","TRANSPORT","S.A.","SPÓŁKA",);

     $oldWords = explode( " " , $name );
     $words = array();

     foreach( $oldWords as $word ){
        if( $word!='' && $word != ' ' ){
            $word = ltrim( rtrim( $word ) );
            if( strlen( $word ) >= 2 && !in_array(strtoupper( $word ), $slowaDoWyciecia))
					$words[] = trim($word);
        }
     }

     $query = "SELECT c.id, c.name,cc.osoba_kon,cc.user_name,cc.data";
     $query .= " FROM bazkl_clients c ";
     $query .= "LEFT OUTER JOIN bazkl_contacts cc ON ";
     $query .= "cc.client_id = c.id ";
     $query .= "WHERE (( upper(c.name) LIKE upper('% ".implode(" %') OR upper(c.name) LIKE upper('% ",$words)." %')) ";
     
     $query .= "OR (upper(c.name) LIKE upper('".implode(" %') OR upper(c.name) LIKE upper('",$words)." %')) ";
     $query .= "OR ( upper(c.name)='".implode("' OR upper(c.name)='", $words)."' ) ";
     $query .= "OR (upper(c.name) LIKE upper('% ".implode("') OR upper(c.name) LIKE upper('% ",$words)."'))) ";
     $query .= "AND c.country=".User::getCountry(User_Session::getUserId())." ";
     $query .= "AND c.id <>".$client_id." AND c.my_user_id is null ORDER BY c.name ASC,cc.data ASC";
     $query = str_replace("OR upper(c.name) LIKE upper('%%')",'',$query);
     $query = str_replace("OR upper(c.name) LIKE upper('% %')",'',$query);
     $query = str_replace("OR upper(c.name) LIKE upper('%  %')",'',$query);
     $result = DBManager::getArrayData($query);
    if(!mysql_error())
        Log::logInfo(Application::prepareLogMessage("Wykonano zapytanie o podobnych klientow {".$query."}", "PrintSimilarClients", "clients"));
    else
        Log::logError(Application::prepareLogMessage("Blad w zapytaniu o podobnych klientow {".mysql_error()."}. Zapytanie{".$query."}", "PrintSimilarClients", "clients"));
     $cl_data = array();
     $keys = "0,";

	if($result)
	{
     foreach($result as $data ){
         if(!strrpos($keys,",".$data[ 'id' ].",")){
             $cl_data[ $data[ 'id' ] ] = array( "id" => $data[ 'id' ],"name" => $data[ 'name' ], "osoba_kon" => $data[ 'osoba_kon' ],
                                                "user_name" => $data[ 'user_name' ], "data" => $data[ 'data' ],
                                                "data1" => "","data2" =>"","osoby" => "" );
             $keys += $data[ 'id' ].",";
        }
     }
	 }
     if( count( $cl_data ) <= 0 )
        $cl_data[] = array("id" => "","name" => "", "osoba_kon" => "",
                                                "user_name" => "", "data" => "",
                                                "data1" => "","data2" =>"","osoby" => "");

     $query = "SELECT client_id,data1,data2,osoby FROM bazkl_realizations where client_id in (".implode( "," , array_keys( $cl_data ) ).") AND client_id <> ".$client_id." ORDER BY client_id ASC,data1 DESC";
     $result = DBManager::getArrayData($query);
     if(!mysql_error())
        Log::logInfo(Application::prepareLogMessage("Wykonano zapytanie o realizacje podobnych klientow {".$query."}", "PrintSimilarClients", "clients"));
    else
        Log::logError(Application::prepareLogMessage("Blad w zapytaniu o realizacje podobnych klientow {".mysql_error()."}. Zapytanie{".$query."}", "PrintSimilarClients", "clients"));
     $cli_real = array();

	 if($result)
	 {
     foreach( $result as $data )
         if ( !in_array( $data[ 'client_id' ], $cli_real ) ){
             $cli_real[] = $data[ 'client_id' ];
             $cl_data[ $data[ 'client_id' ] ][ 'data1' ] = $data[ 'data1' ];
             $cl_data[ $data[ 'client_id' ] ][ 'data2' ] = $data[ 'data2' ];
             $cl_data[ $data[ 'client_id' ] ][ 'osoby' ] = $data[ 'osoby' ];
         }
	 }
     $sim_clients .="<table cellspacing='0' cellpadding='0' border='1' style='background-color:#cccccc'>"."\n";
     $sim_clients .= "<tr style='background-color:white' border='0px'><td colspan=8><font color='red'><b>".__('Klienci i firmy o podobnych nazwach w bazie:')."</b></font></td></tr>"."\n";
     $sim_clients .= "<tr style='background-color:#ddcccc'>";
     $sim_clients .= "<td><b>".__('Nazwa')."</b></td>";
     $sim_clients .= "<td><b>".__('Osoba Kontaktowa')."</b></td>";
     $sim_clients .= "<td><b>".__('Kontakt')."</b></td>";
     $sim_clients .= "<td><b>".__('Data Kontaktu')."</b></td>";
     $sim_clients .= "<td><b>".__('Realizacja')."</b></td>";
     $sim_clients .= "<td><b>".__('Data Początku')."</b></td>";
     $sim_clients .= "<td><b>".__('Data Końca')."</b></td>";
     $sim_clients .= "</tr>"."\n";

     $data1Month = date("Y-m-d",strtotime('-1 month'));

     foreach( $cl_data as $key =>$data){
         if ( $data['id'] != "0" && $key!=0){
            $bgCol = "cccccc";
            if( $data['data'] < $data1Month )
                $bgCol = "FFC1C1";

            $sim_clients .= "<tr style='background-color:#".$bgCol."'>";
            $sim_clients .= "<td><a href='index.php?action=clients&site=show&id=".$data['id']."'>".$data['name']."</a></td>";
            $sim_clients .= "<td>".(($data['osoba_kon']=="")?("---"):($data['osoba_kon']))."</td>";
            $sim_clients .= "<td>".(($data['user_name']=="")?("---"):($data['user_name']))."</td>";
            $sim_clients .= "<td>".(($data['data']=="")?("---"):($data['data']))."</td>";
            $sim_clients .= "<td>".(($data['osoby']=="")?("---"):($data['osoby']))."</td>";
            $sim_clients .= "<td>".(($data['data1']=="")?("---"):($data['data1']))."</td>";
            $sim_clients .= "<td>".(($data['data2']=="")?("---"):($data['data2']))."</td>";
            $sim_clients .= "</tr>"."\n";
        }
     }
     $sim_clients .= "</table>"."\n";
     return $sim_clients;
   }
?>